// repositories/user.go
package repositories

import (
	"fmt"
	"myapi/models"
)

// UserRepository 处理用户数据库操作
type UserRepository struct{}

// Create 创建新用户
func (r *UserRepository) Create(user *models.User) error {
	return DB.Create(user).Error
}

// FindByID 通过 ID 查找用户
func (r *UserRepository) FindByID(id uint) (*models.User, error) {
	var user models.User
	err := DB.First(&user, id).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

// FindByEmail 通过邮箱查找用户
func (r *UserRepository) FindByEmail(email string) (*models.User, error) {
	var user models.User
	err := DB.Where("email = ?", email).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

// FindAll 获取所有用户
func (r *UserRepository) FindAll(page, pageSize int) ([]models.User, int64, error) {
	var users []models.User
	var count int64

	offset := (page - 1) * pageSize
	// 获取总数
	if err := DB.Model(&models.User{}).Count(&count).Error; err != nil {
		return nil, 0, err
	}
	// 获取分页数据
	if err := DB.Offset(offset).Limit(pageSize).Find(&users).Error; err != nil {
		return nil, 0, err
	}
	fmt.Println(users)
	return users, count, nil
}

// Update 更新用户信息
func (r *UserRepository) Update(user *models.User) error {
	return DB.Save(user).Error
}

// Delete 删除用户
func (r *UserRepository) Delete(id uint) error {
	return DB.Delete(&models.User{}, id).Error
}
